<template>
  <div class="px-[16px] py-[16px] mt-[8px] bg-[var(--base-color)] rounded-[8px]">
    <FormTitle title="物流商地址信息" />
    <vxe-table
      ref="tableRef"
      :data="data"
      border="full"
      :round="true"
      maxHeight="400"
    >
      <vxe-column title="地址编码" fixed="left" width="128">
        <template #default="{ row }">
          <el-input v-model="row.address_code" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="地址名称" width="200">
        <template #default="{ row }">
          <el-input v-model="row.address_name" clearable v-if="notAdd(row)" />
          <el-button v-if="row.type === 'add'" @click="handleAddRow">
            +添加
          </el-button>
        </template>
      </vxe-column>
      <vxe-column title="地址" min-width="200">
        <template #default="{ row }">
          <el-input v-model="row.address" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="提货联系人" width="200">
        <template #default="{ row }">
          <el-input v-model="row.pickup" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="提货联系人电话" width="200">
        <template #default="{ row }">
          <el-input v-model="row.pickup_tel" clearable v-if="notAdd(row)" />
        </template>
      </vxe-column>
      <vxe-column title="操作" width="100">
        <template #default="{ row, rowIndex }">
          <el-button
            type="danger"
            link
            v-if="notAdd(row)"
            @click="handleDelete(rowIndex)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script setup lang="jsx">
import FormTitle from '@/components/Form/FormTitle.vue'

const props = defineProps({
  data: { type: Object, default: () => ({}) },
})

const tableData = ref([{ type: 'add' }])

const emit = defineEmits(['update:modelValue', 'refresh'])

const tableRef = ref()

const data = computed(() => {
  return tableData.value.filter(n => n.is_delete !== 1)
})

watch(
  () => props.data,
  val => {
    const { address_details = [] } = val || {}
    if (!address_details.length) return
    tableData.value = address_details.concat({
      type: 'add',
    })
  }
)

const getTableData = () => {
  try {
    const _data = tableData.value
    return _data.filter(n => n.type !== 'add')
  } catch (e) {
    console.warn(e)
    return []
  }
}

const handleAddRow = async () => {
  tableData.value.splice(-1, 0, {})
  await nextTick()
  tableRef.value?.loadData(tableData.value).then(() => {
    const el = tableRef.value.$el.querySelector('.vxe-table--body-wrapper')
    if (el) {
      el.scrollTop = el.scrollHeight
    }
  })
}

const handleDelete = index => {
  tableData.value[index].is_delete = 1
  tableData.value.splice(index, 1)
}

const notAdd = row => row.type !== 'add'

defineExpose({ getTableData })
</script>
